package com.ttfeed.server.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLockUtil {

    private final static Logger logger = LoggerFactory.getLogger(RedisLockUtil.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取锁重试时间
     **/
    private static final long TRY_TIME = 3 * 1000;

    /**
     * 加锁
     *
     * @param key
     * @param value
     * @param seconds
     * @return
     */
    public boolean lockNoTry(String key, String value, long seconds) {
        if (stringRedisTemplate.opsForValue().setIfAbsent(key, value, seconds, TimeUnit.SECONDS)) {
            return true;
        }
        return false;
    }

    /**
     * 尝试加锁
     *
     * @param key
     * @param value
     * @param seconds
     * @return
     */
    public boolean lock(String key, String value, long seconds) {
        long currentTime = System.currentTimeMillis();
        while (System.currentTimeMillis() - currentTime < TRY_TIME) {
            if (stringRedisTemplate.opsForValue().setIfAbsent(key, value, seconds, TimeUnit.SECONDS)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 解锁
     *
     * @param key
     * @param value
     */
    public void unlock(String key, String value) {
        try {
            if (String.valueOf(stringRedisTemplate.opsForValue().get(key)).equals(value)) {
                stringRedisTemplate.opsForValue().getOperations().delete(key);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
